const path = require('path');
const Config = require('webpack-chain');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
// const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');

const resolve = (dir) => path.join(__dirname, '../..', dir);

const packageJSON = require('../../package.json');

const config = new Config();

const createStyleRule = (name, test) => config.module.rule(name)
  .test(test)
  .use('cache-loader')
  .loader('cache-loader')
  .end()
  .use('vue-style-loader')
  .loader('vue-style-loader')
  .end()
  .use('css-loader')
  .loader('css-loader')
  .end()
  .use('scoped-css-loader')
  .loader('scoped-css-loader')
  .end()
  .use('postcss-loader')
  .loader('postcss-loader')
  .end();

config.mode('none');

config.entry('index')
  .add('react-hot-loader/patch')
  .add(resolve('./src/index.tsx'));

config.output
  .path(resolve('build'))
  .filename('[name].js')
  .chunkFilename('[name].js')
  .publicPath('/');

config.resolve.extensions
  .merge(['.ts', '.tsx', '.js', '.jsx', '.json']);

config.resolve.alias
  .set('~', resolve('src'))
  .set('react-dom', '@hot-loader/react-dom');

// config.module.rule('eslint')
//   .test(/\.(tsx?|jsx?)$/)
//   .enforce('pre')
//   .use('eslint')
//   .loader('eslint-loader')
//   .end()
//   .exclude.add(/node_modules/);

config.module.rule('ts')
  .test(/\.tsx?$/)
  .use('cache-loader')
  .loader('cache-loader')
  .end()
  .use('thread-loader')
  .loader('thread-loader')
  .options({ workers: 2 })
  .end()
  .use('babel')
  .loader('babel-loader')
  .end()
  .use('ts')
  .loader('ts-loader')
  .options({ happyPackMode: true, transpileOnly: true })
  .end()
  .exclude.add(/node_modules/);

config.module.rule('js')
  .test(/\.jsx?$/)
  .use('babel')
  .loader('babel-loader')
  .end()
  .exclude.add(/node_modules/);

createStyleRule('css', /\.css$/);

createStyleRule('sass', /\.(sass|scss)$/)
  .use('sass-loader')
  .loader('sass-loader')
  .end();

createStyleRule('less', /\.less$/)
  .use('less-loader')
  .loader('less-loader')
  .options({
    javascriptEnabled: true,
  })
  .end();

config.module.rule('images')
  .test(/\.(jpe?g|png|gif|svg)$/i)
  .use('url-loader')
  .loader('url-loader')
  .options({
    limit: 10240,
  })
  .end();

config.plugin('fork-ts-checker-webpack-plugin')
  .use(ForkTsCheckerWebpackPlugin, [{ eslint: true }]);

// config.plugin('antd-dayjs-webpack-plugin')
//   .use(AntdDayjsWebpackPlugin);

// base path
config.plugin('html-webpack-plugin')
  .use(HtmlWebpackPlugin, [{
    template: path.join(__dirname, '../../public/index.html'),
    templateParameters: {
      PUBLIC_URL: packageJSON.basePath || '',
    },
  }]);

module.exports = config;
